package DB;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import Data.FileData;
import Data.FileManager;


/**
 * renaming a file in the files table in DB
 * @author Erez
 *
 */

public class RenameFile
{
	public RenameFile() 
	{
		
	}
	
    /**
     * opens a session with DB and search for file name that equals oldname
     * if a file name is found than it is replaced with the new file name 
     * and the file is saved in DB
     * at the end the change is saved in the array of changes
     * @param oldname the old file name 
     * @param newname the new file name
     */
	public synchronized void renameInDB(String oldname, String newname)
	{
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        FileManager manager = new FileManager(session);
    	Query query = session.createQuery("from FileData");
    	@SuppressWarnings("unchecked")
    	List<FileData> list = query.list();
    	Iterator<FileData> it=list.iterator();
    	FileData file;
    	while (it.hasNext())
    	{
    		file=it.next();
    		if(file.getName().equals(oldname)==true)
    		{
    			file.setName(newname);
    			manager.updateFile(file);
    		}		
    		
    	}
    	session.flush();
    	ArrayOfChanges.instance.addChange("renamed "+ oldname +newname);
	}
}
